package com.example.sspulibrary.fragment;

import static android.content.Context.MODE_PRIVATE;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton.OnCheckedChangeListener;

import android.os.Handler;
import android.os.Message;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sspulibrary.MainActivity;
import com.example.sspulibrary.R;
import com.example.sspulibrary.adapter.SpinnerAdapter;
import com.example.sspulibrary.db.DBDefinitionManipulation;
import com.example.sspulibrary.model.Book;
import com.example.sspulibrary.model.ExceptBook;
import com.example.sspulibrary.tools.Util;
import com.example.sspulibrary.adapter.EPCAdapter;
import com.example.sspulibrary.model.EpcDataModel;
import com.uhf.api.cls.Reader.TAGINFO;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.pda.serialport.Tools;


public class ScanFragment extends Fragment implements OnCheckedChangeListener, OnClickListener {
    @Nullable
    private Button btnStart, btnExcept, btnClear;//inventory button扫描开始按钮
    private boolean isMulti = false;// multi mode flag多标签模式勾选,默认为false不改变
    private CheckBox checkMulti;//multi model check box 勾选框


    private View view;// this fragment UI
    private boolean isTid = true;// multi mode flag
    private boolean isPlay = true;// multi mode flag
    private int allCount = 0;// inventory count

    private Set<String> epcSet = null; //store different EPC
    private List<EpcDataModel> listEpc = null;//EPC list
    private List<EpcDataModel> exceptList = null;//EPC list
    private Map<String, Integer> mapEpc = null; //store EPC position //显示的标签
    private EPCAdapter adapter, exceptListAdapter;//epc list adapter //adapter 调用展示列表方法
    private ListView lvEpc, exceptListView;// epc list view 列表展示?

    DBDefinitionManipulation db;


    private TextView houseTv, rowTv, faceTv, seriesTv;
    Spinner spinnerScan;
    String[] houseArray;


    private Runnable runnable_MainActivity = new Runnable() {

        @Override
        public void run() {
            List<TAGINFO> list1;
            if (isMulti) {
                list1 = MainActivity.mUhfrManager.tagInventoryRealTime();
            } else {
                if (isTid) {
                    list1 = MainActivity.mUhfrManager.tagEpcTidInventoryByTimer((short) 50);
                } else {
                    list1 = MainActivity.mUhfrManager.tagInventoryByTimer((short) 50);
                }
            }
            String data;
            handler1.sendEmptyMessage(1980);
            if (list1 != null && list1.size() > 0) {
                if (isPlay) {
                    Util.play(1, 0);
                }
                for (TAGINFO tfs : list1) {
                    byte[] epcdata = tfs.EpcId;
                    if (isTid) {
                        data = Tools.Bytes2HexString(tfs.EmbededData, tfs.EmbededDatalen);
                    } else {
                        data = Tools.Bytes2HexString(epcdata, epcdata.length);
                    }
                    int rssi = tfs.RSSI;
                    Message msg = new Message();
                    msg.what = 1;
                    Bundle b = new Bundle();
                    b.putString("data", data);
                    b.putString("rssi", rssi + "");
                    msg.setData(b);
                    handler1.sendMessage(msg);
                }
            }
            handler1.postDelayed(runnable_MainActivity, 0);
        }
    };
    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String epc = msg.getData().getString("data");
                    String rssi = msg.getData().getString("rssi");
                    if (epc == null || epc.length() == 0) {
                        return;
                    }
                    int position;
                    allCount++;
                    if (epcSet == null) {//first
                        epcSet = new HashSet<String>();
                        listEpc = new ArrayList<EpcDataModel>();
                        mapEpc = new HashMap<String, Integer>();
                        epcSet.add(epc);
                        mapEpc.put(epc, 0);
                        EpcDataModel epcTag = new EpcDataModel();
                        epcTag.setepc(epc);
                        epcTag.setrssi(rssi);
                        if (!listEpc.contains(epcTag)) {
                            listEpc.add(epcTag);
                        }
                        adapter = new EPCAdapter(getActivity(), listEpc, "listEpc");
//                        Log.e("aa", "listEpc.size():" + listEpc.size());
//                        Log.e("aa", "epcTag:" + epcTag);
                        lvEpc.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                        MainActivity.mSetEpcs = epcSet;
                    } else {
                        if (epcSet.contains(epc)) {//set already exit
                            position = mapEpc.get(epc);
                            EpcDataModel epcOld = listEpc.get(position);
                            epcOld.setrssi(rssi);

                            listEpc.set(position, epcOld);
                        } else {
                            epcSet.add(epc);
                            mapEpc.put(epc, listEpc.size());
                            EpcDataModel epcTag = new EpcDataModel();
                            epcTag.setepc(epc);
                            epcTag.setrssi(rssi);
                            if (!listEpc.contains(epcTag)) {
                                listEpc.add(epcTag);
                            }
                            MainActivity.mSetEpcs = epcSet;
                        }
//                        tvTagCount.setText("" + allCount);
//                        tvTagSum.setText("" + listEpc.size());//不需要 tag总数
                        adapter.notifyDataSetChanged();
                    }
                    break;
                case 1980:
//                    String countString = tvRunCount.getText().toString();
//                    if (countString.equals("") || countString == null) {
//                        tvRunCount.setText(String.valueOf(1));
//                    } else {
//                        int previousCount = Integer.valueOf(countString);
//                        int nowCount = previousCount + 1;
//                        tvRunCount.setText(String.valueOf(nowCount));
//                    }
                    break;
            }
        }
    };


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.scanhome_fragment, null);
        initDB();
        initView();


        return view;
    }

    public void initDB() {
        db = new DBDefinitionManipulation(getContext());
        db.open();

        db.getDatas();
        this.houseArray = process("StoreHouse");
        db.close();
    }

    //初始化
    private void initView() {
        btnStart = (Button) view.findViewById(R.id.button_start);
        btnExcept = (Button) view.findViewById(R.id.button_export);
        btnClear = (Button) view.findViewById(R.id.button_clear_epc);


        btnStart.setOnClickListener(this);//
        btnExcept.setOnClickListener(this);
        btnClear.setOnClickListener(this);//
        lvEpc = (ListView) view.findViewById(R.id.listView_epc);
        exceptListView = (ListView) view.findViewById(R.id.listView_except_list);
//        checkMulti = (CheckBox) view.findViewById(R.id.checkBox_multi);
//        checkMulti.setOnCheckedChangeListener(this);//多标签功能

        houseTv = view.findViewById(R.id.scan_storeHouse);
        rowTv = view.findViewById(R.id.scan_row);
        faceTv = view.findViewById(R.id.scan_face);
        seriesTv = view.findViewById(R.id.scan_series);
    }


    private String[] process(String item) {
        SharedPreferences preferences = getContext().getSharedPreferences("DBBookInfo", MODE_PRIVATE);
        String string = preferences.getString(item, "");
        String replace = string.replace("[", "");
        String replace1 = replace.replace("]", "");

        String[] split = replace1.split(",");


        return split;
    }

    private boolean keyControl = true;

    public void isRead() {
        if (exceptList == null) {
            exceptList = Collections.emptyList();
        }
        if (listEpc == null) {
            listEpc = Collections.emptyList();
        }

        Util.initSoundPool(getContext());
        if (MainActivity.mUhfrManager == null) {
            showToast(getActivity().getString(R.string.connection_failed));
            return;
        }
        if (!isStart) {
            showCustomizeDialog();
//            checkMulti.setEnabled(false);
            btnStart.setText(this.getString(R.string.stop_inventory_epc));
            MainActivity.mUhfrManager.setGen2session(isMulti);
            if (isMulti) {
//                Log.e(TGA, "isMulti-true");
                MainActivity.mUhfrManager.asyncStartReading();
            }
            handler1.postDelayed(runnable_MainActivity, 0);
            isStart = true;
        } else {
//            checkMulti.setEnabled(true);
            if (isMulti) {
//                Log.e(TGA, "isMulti-true");
                MainActivity.mUhfrManager.asyncStopReading();
            }

            handler1.removeCallbacks(runnable_MainActivity);
            btnStart.setText(this.getString(R.string.start_inventory_epc));
            isStart = false;
            if (!listEpc.isEmpty()) {
                exceptList = new ArrayList<>();
                exceptList.clear();
                operate(listEpc);
            }
        }
    }


    private void operate(List<EpcDataModel> list) {
        if (list != null) {
            for (EpcDataModel  epcDataModel : list) {
                Log.e("bb",  epcDataModel.toString());
                db.open();
                boolean b = db.queryByRFID((epcDataModel.getepc()));
                if (!b) {
                    epcDataModel.setBookName(db.queryNameByRFID(epcDataModel.getepc()));
                    exceptList.add(epcDataModel);
                }
                db.close();
            }
            exceptListAdapter = new EPCAdapter(getActivity(), exceptList, "exceptList");
            exceptListView.setAdapter(exceptListAdapter);
        }
    }
    //show tips
    private Toast toast;

    private void showToast(String info) {
        if (toast == null) toast = Toast.makeText(getActivity(), info, Toast.LENGTH_SHORT);
        else toast.setText(info);
        toast.show();
    }


    // 提示框
    private void showCustomizeDialog() {

        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(getContext());
        final View dialogView = LayoutInflater.from(getContext())
                .inflate(R.layout.dialog_customize, null);
        customizeDialog.setTitle("设置检索信息");
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取EditView中的输入内容
                        EditText edit_text_house =
                                (EditText) dialogView.findViewById(R.id.edit_text_house);
                        EditText edit_text_row =
                                (EditText) dialogView.findViewById(R.id.edit_text_row);
                        EditText edit_text_face =
                                (EditText) dialogView.findViewById(R.id.edit_text_face);
                        EditText edit_text_series =
                                (EditText) dialogView.findViewById(R.id.edit_text_series);

//                        Spinner spinnerHouse = dialogView.findViewById(R.id.spinner_house);

//                        ArrayAdapter<String> adapter = new ArrayAdapter<>(dialogView.getContext(), android.R.layout.simple_spinner_item,
//                                houseArray);
//
//                        Log.e("showCustomizeDialog", "" + houseArray.length);
//                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
////                        spinnerHouse.setAdapter(new SpinnerAdapter(dialogView.getContext(), process("StoreHouse")));
//                        spinnerHouse.setAdapter(adapter);
//
//                        spinnerHouse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                            @Override
//                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
////                                String result = parent.getItemAtPosition(position).toString(); 	//获取选择项的值
////                                Toast.makeText(dialogView.getContext(),result,Toast.LENGTH_SHORT).show(); //显示被选中的值
//                                Log.e("onItemSelected", "" + position);
//                            }
//
//                            @Override
//                            public void onNothingSelected(AdapterView<?> parent) {
//
//                            }
//                        });


                        SharedPreferences info = getContext().getSharedPreferences("info", MODE_PRIVATE);
                        SharedPreferences.Editor editor = info.edit();
                        editor.clear();
                        editor.putString("searchHouse", edit_text_house.getText().toString());
                        editor.putString("searchRow", edit_text_row.getText().toString());
                        editor.putString("searchFace", edit_text_face.getText().toString());
                        editor.putString("searchSeries", edit_text_series.getText().toString());
                        editor.apply();
                        houseTv.setText(edit_text_house.getText().toString());
                        rowTv.setText(edit_text_row.getText().toString());
                        faceTv.setText(edit_text_face.getText().toString());
                        seriesTv.setText(edit_text_series.getText().toString());
                    }
                });
        customizeDialog.show();
    }


    private boolean isStart = false;


    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_start:
                isRead();
                break;
            case R.id.button_clear_epc:
                clearEpc();
                break;
            case R.id.button_export:
                if (exceptList == null) {
                    exceptList = Collections.emptyList();
                }
                if (!exceptList.isEmpty()) {
                    db.open();
//                    db.deleteAllExceptBook();
                    for (EpcDataModel epcDataModel : exceptList) {
                        ExceptBook exceptBook = new ExceptBook();
                        Book book = db.getBookByRFID(epcDataModel.getepc());

                        exceptBook.setBookName(book.getBookName());
                        exceptBook.setBookRFID(epcDataModel.getepc());
                        exceptBook.setCurrentTime(new Date(System.currentTimeMillis()).toString());
                        exceptBook.setRightLocation(book.getStoreHouse() + "库" + book.getRow() + "排" +
                                book.getFace() + "面" + book.getSeries() + "列");
                        exceptBook.setCurrentLocation(houseTv.getText().toString() + "库" + rowTv.getText().toString() + "排" + faceTv.getText().toString() + "面" + seriesTv.getText().toString() + "列");

//                        Log.e("xxx", exceptBook.toString());
                        db.addExceptBook(exceptBook);
                    }
                    db.close();
                    showToast("保存成功！");
                } else {
                    showToast("数据为空!");
                }
                break;
        }
    }

    private void clearEpc() {
        if (exceptList == null) {
            exceptList = Collections.emptyList();
        }
        if (listEpc == null) {
            listEpc = Collections.emptyList();
        }
        exceptList.clear();
        listEpc.clear();
        exceptListAdapter = new EPCAdapter(getActivity(), exceptList, "exceptList");
        exceptListView.setAdapter(exceptListAdapter);
        adapter = new EPCAdapter(getActivity(), listEpc, "listEpc");
        lvEpc.setAdapter(adapter);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
        switch (buttonView.getId()) {
//            case R.id.checkBox_multi:
//                if (isChecked) {
//                    isMulti = true;
//                } else {
//                    isMulti = false;
//                }
//                break;
        }
    }
}
